package com.dsunsoft.rtu.netty;

import io.netty.channel.Channel;
import io.netty.channel.socket.SocketChannel;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 存放连接的channel对象
 */
public class NettyChannelMap {
    private static final Map<Integer, SocketChannel> CHANNEL_MAP = new ConcurrentHashMap<Integer, SocketChannel>();

    /**
     * 添加客户端
     *
     * @param clientId      clientId
     * @param socketChannel socketChannel
     */
    public static void add(Integer clientId, SocketChannel socketChannel) {
        CHANNEL_MAP.put(clientId, socketChannel);
    }

    /**
     * 获取所有客户端
     *
     * @return all
     */
    public static Map<Integer, SocketChannel> get() {
        return CHANNEL_MAP;
    }

    /**
     * 获取客户端
     *
     * @param clientId clientId
     * @return socketChannel
     */
    public static Channel get(Integer clientId) {
        return CHANNEL_MAP.get(clientId);
    }

    /**
     * 移除客户端
     *
     * @param socketChannel socketChannel
     */
    public static void remove(SocketChannel socketChannel) {
        for (Map.Entry<Integer, SocketChannel> entry : CHANNEL_MAP.entrySet()) {
            if (entry.getValue().equals(socketChannel)) {
                CHANNEL_MAP.remove(entry.getKey());
            }
        }
    }
}